import logging
import hashlib
import uuid
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
from passlib.handlers.pbkdf2 import pbkdf2_sha256
from fastapi import Depends, HTTPException
from .user_data import server_user_data

logger = logging.getLogger(__name__)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/dev/token")


def return_code(code: int, data=None, msg="sucess") -> dict:
    if data:
        return {"code": code, "msg": msg, "data": data}
    return {"code": code, "msg": msg}


def random_str() -> str:
    return "1002b56fcd94" + str(hashlib.md5(str(uuid.uuid1()).encode(encoding="UTF-8")).hexdigest())


def en_password(psw: str) -> str:
    """
    密码加密
    """
    return pbkdf2_sha256.hash(psw)


def check_password(password: str, old: str) -> bool:
    """
    密码校验
    """
    check = pbkdf2_sha256.verify(password, old)
    if check:
        return True
    return False


async def auth_depend(token: str = Depends(oauth2_scheme)):
    user_data = server_user_data.get_user(token)
    return user_data


async def is_admin_user(security_scopes: SecurityScopes, user: dict = Depends(auth_depend)):
    if "allow" in security_scopes.scopes:
        return user
    raise HTTPException(status_code=401, detail=u"无权限访问")


def analysis_data(data_list: list, field_list: list):
    data_field_list = []
    for item in data_list:
        data_dict = {}
        index = 0
        for field in field_list:
            data_dict[field] = item[index]
            index += 1
        data_field_list.append(data_dict)
    return data_field_list
